package com.basker.pisces.core.query;

import com.basker.pisces.core.enums.AggregateType;
import com.basker.pisces.core.query.meta.FieldDesc;

/**
 * 聚合字段,在{@link SelectField}的基础上，定义了聚合类型{@link AggregateType}
 *
 * @author hangwen
 */
public class AggregateField extends SelectField {
    private AggregateType type = AggregateType.None;

    public AggregateField() {

    }

    /**
     * 通过{@link FieldDesc}创建
     *
     * @param fieldDesc
     * @param type
     */
    public AggregateField(FieldDesc fieldDesc, AggregateType type) {
        super(fieldDesc.getId(), fieldDesc.getAlias());
        this.type = type;
    }

    /**
     * id和别名一致
     *
     * @param id
     * @param type
     */
    public AggregateField(String id, AggregateType type) {
        super(id, id);
        this.type = type;
    }

    /**
     * 具体指定id和别名
     *
     * @param id
     * @param alias
     * @param type
     */
    public AggregateField(String id, String alias, AggregateType type) {
        super(id, alias);
        this.type = type;
    }

    @Override
    public String genSelectExpression(FieldDesc fieldDesc) {
        String selectExpression = super.genSelectExpression(fieldDesc);

        if (this.supportAggregate()) {
            return String.join("", this.type.getName(), "(", selectExpression, ")");
        } else {
            return selectExpression;
        }

    }

    public AggregateType getType() {
        return type;
    }

    public void setType(AggregateType type) {
        this.type = type;
    }

    private boolean supportAggregate() {
        return this.type != null && !this.type.equals(AggregateType.None);
    }

}
